package zx.x.modules.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import zx.x.common.utils.R;
import zx.x.modules.app.entity.DybEntity;
import zx.x.modules.app.entity.OrderEntity;
import zx.x.modules.app.entity.SysOrderLogEntity;
import zx.x.modules.app.entity.UserEntity;
import zx.x.modules.app.pw.Card;
import zx.x.modules.app.pw.pw;
import zx.x.modules.app.service.DybService;
import zx.x.modules.app.service.SysOrderLogService;
import zx.x.modules.app.service.UserService;
import zx.x.modules.app.utils.PayUtil;
import zx.x.modules.app.utils.WechatConfig;
import zx.x.modules.common.service.CreativeGoodsService;
import zx.x.modules.yshapp.entity.MemberEntity;
import zx.x.modules.yshapp.entity.YOrderEntity;
import zx.x.modules.yshapp.service.MemberService;
import zx.x.modules.yshapp.service.OrderService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/app/wx")
public class WxController {
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    @Autowired
    SysOrderLogService sysOrderLogService;
    @Autowired
    private CreativeGoodsService creativeGoodsService;
    @Autowired
    private pw pw;
    @Autowired
    private DybService dybService;
    @Autowired
    private MemberService memberService;

    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    public R wxPay(Long userId,String orderNo,HttpServletRequest request) {
        Map<String, Object> response = new HashMap<String, Object>();//返回给小程序端需要的参数
        UserEntity u = userService.getById(userId);
        try {
            //生成的随机字符串
            String nonce_str = getRandomStringByLength(32);

            //获取客户端的ip地址
            String spbill_create_ip = getIpAddr(request);

            // 获取订单信息
            QueryWrapper<YOrderEntity> queryWrapper = new QueryWrapper<YOrderEntity>();
            queryWrapper.eq("order_no", orderNo);
            YOrderEntity orderEntity = orderService.getOne(queryWrapper);
            BigDecimal price = new BigDecimal(String.valueOf(orderEntity.getPrice())).multiply(new BigDecimal("100"));

            String body = "";
            //订单类型：1会员2福利商品3生活商品
            if (orderEntity.getType() == 1 ){
                body = "会员";
            }else if (orderEntity.getType() == 2){
                body = "福利商品";
            }else if (orderEntity.getType() == 3){
                body = "生活商品";
            }

            // 订单号
            String payOrderId = orderNo;

            // open_id
            String openId = u.getOpenid();

            //组装参数，用户生成统一下单接口的签名
            Map<String, String> packageParams = new HashMap<>();
            packageParams.put("appid", WechatConfig.appid);
            packageParams.put("body", body);
            packageParams.put("mch_id", WechatConfig.mch_id);
            packageParams.put("nonce_str", nonce_str);
            packageParams.put("notify_url", WechatConfig.notify_url);//支付成功后的回调地址
            packageParams.put("openid", openId + "");//用户的openID，自己获取
            packageParams.put("out_trade_no", payOrderId + "");//商户订单号,自己的订单ID
            packageParams.put("spbill_create_ip", spbill_create_ip);
            packageParams.put("total_fee", price.stripTrailingZeros().toPlainString() + "");//支付金额，这边需要转成字符串类型，否则后面的签名会失败
            packageParams.put("trade_type", WechatConfig.TRADETYPE);//支付方式

            String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串

            //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口
            String mysign = PayUtil.sign(prestr, WechatConfig.key, "utf-8").toUpperCase();


            //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去
            String xml = "<xml>\n" + "<appid>" + WechatConfig.appid + "</appid>\n"
                    + "<body>"+body+"</body>\n"
                    + "<mch_id>" + WechatConfig.mch_id + "</mch_id>\n"
                    + "<nonce_str>" + nonce_str + "</nonce_str>\n"
                    + "<notify_url>" + WechatConfig.notify_url + "</notify_url>\n"
                    + "<openid>" + openId + "</openid>\n"
                    + "<out_trade_no>" + payOrderId + "</out_trade_no>\n"
                    + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>\n"
                    + "<total_fee>" + price.stripTrailingZeros().toPlainString() + "</total_fee>\n"//支付的金额，单位：分
                    + "<trade_type>" + WechatConfig.TRADETYPE + "</trade_type>\n"
                    + "<sign>" + mysign + "</sign>\n"
                    + "</xml>";


            //调用统一下单接口，并接受返回的结果
            String result = PayUtil.httpRequest(WechatConfig.pay_url, "POST", xml);

            // 将解析结果存储在HashMap中
            Map map = PayUtil.doXMLParse(result);

            String return_code = (String) map.get("return_code");//返回状态码
            String result_code = (String) map.get("result_code");//返回状态码

            if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
                String prepay_id = (String) map.get("prepay_id");//返回的预付单信息
                response.put("nonceStr", nonce_str);
                response.put("prepayId", prepay_id);
                Long timeStamp = System.currentTimeMillis() / 1000;
                response.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误
                //拼接签名需要的参数
                String stringSignTemp = "appId=" + WechatConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
                //再次签名，这个签名用于小程序端调用wx.requesetPayment方法
                String paySign = PayUtil.sign(stringSignTemp, WechatConfig.key, "utf-8").toUpperCase();
                response.put("paySign", paySign);
            }

            response.put("appid", WechatConfig.appid);
            return R.ok().put("response",response).put("orderId",orderEntity.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //这里是支付回调接口，微信支付成功后会自动调用
    @RequestMapping(value = "/wxNotify", method = RequestMethod.POST)
    @Transactional
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        //sb为微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";

        Map map = PayUtil.doXMLParse(notityXml);

        QueryWrapper<YOrderEntity> queryWrapper = new QueryWrapper<YOrderEntity>();
        queryWrapper.eq("order_no", map.get("out_trade_no"));
        YOrderEntity orderEntity = orderService.getOne(queryWrapper);
        if ("SUCCESS".equals(map.get("return_code"))) {
            // 查询出订单，而且未付款，继续往下走流程
            if (orderEntity != null && 0 == orderEntity.getOrderState()) {
                //验证签名是否正确
                Map<String, String> validParams = PayUtil.paraFilter(map);  //回调验签时需要去除sign和空值参数
                String prestr = PayUtil.createLinkString(validParams);
                //根据微信官网的介绍，此处不仅对回调的参数进行验签，还需要对返回的金额与系统订单的金额进行比对等
                if (PayUtil.verify(prestr, (String) map.get("sign"), WechatConfig.key, "utf-8")) {

                    //修改用户会员到期时间和类型
                    MemberEntity memberEntity = memberService.getById(orderEntity.getGoodsId());
                    UserEntity user = userService.getById(orderEntity.getUserId());
                    Date date = user.getMemberEndTime();
                    if(user.getMemberEndTime() ==null){
                        date = new Date();
                    }
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(date);   //设置当前时间
                    if(memberEntity.getTimeType() ==1){
                        cal.add(Calendar.YEAR, 1);  //一年
                    }else if(memberEntity.getTimeType() == 2){
                        cal.add(Calendar.MONTH, 3);//一个季度
                    }else{
                        cal.add(Calendar.MONTH, 1);//一个月
                    }
                    user.setMemberEndTime(cal.getTime());//过期时间
                    user.setType(memberEntity.getType());//会员类型
                    userService.updateById(user);

                    // 修改订单
                    orderEntity.setOrderState(1);//已支付
                    orderEntity.setPayTime(new Date());
                    orderEntity.setWxTransaction((String) map.get("transaction_id"));
                    orderService.updateById(orderEntity);

                    //注意要判断微信支付重复回调，支付成功后微信会重复的进行回调
//                    System.out.println("========================测试支付");
                    /**此处添加自己的业务逻辑代码end**/
                    //通知微信服务器已经支付成功
                }
            }
            resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        } else {
            resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
        }

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }

    //获取随机字符串
    private String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    //获取IP
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}
